package cn.sky.demo.sso;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

@Component
public class SessionAuthenticationFilter implements Filter{

    private static  final String LOGIN_PAGE="http://auth.example.com/auth/login";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest= (HttpServletRequest) request;
        HttpServletResponse httpResponse= (HttpServletResponse) response;

        // 公开路径不需要认证
        String path= httpRequest.getRequestURI();
        if (isPublicPath(path)) {
            chain.doFilter(request, response);
            return;
        }

        // 检查session中是否有用户信息
        HttpSession session= httpRequest.getSession(false);
        boolean authenticated= session != null && session.getAttribute("USER_INFO") != null;

        if (authenticated) {
            // 用户已认证，继续请求
            chain.doFilter(request, response);
        } else {
            // 未认证，重定向到登录页面
            String redirectUrl= LOGIN_PAGE + "?redirect=" +
                    URLEncoder.encode(httpRequest.getRequestURL().toString(), "UTF-8");
            httpResponse.sendRedirect(redirectUrl);
        }
    }

    private boolean isPublicPath(String path) {
        return path.startsWith("/public/") ||
                path.startsWith("/resources/") ||
                path.equals("/error");
    }
}